<template>
  <view class="mt-2 mb-2 c-text-14">安全守护</view>

  <view class="c-br bg-white px-1 py-1">
    <van-grid clickable :border="false" column-num="4">
      <van-grid-item use-slot v-for="(item, index) in operatorList" @click="operatorClick(item.type)" :key="index">
        <i :class="[item.iconPath, 'font-size-8 mb-2']"></i>
        <text class="c-text-12">{{ item.name }}</text>
      </van-grid-item>
    </van-grid>

    <van-popup position="bottom" :show="dataForm.popupShow" @close="onClose">
      <view class="top flex items-center px-2 py-2 box-border">
        <view class="w-20%"></view>
        <view class="w-60% text-align-center">
          <text class="c-text-16">{{ dataForm.selectType === 'startExamine' ? '开始检测' : '定时检测' }}</text>
        </view>
        <view class="w-20% text-align-end" @click="onClose"><i class="i-mdi:close w-6 h-6"></i></view>
      </view>
      <view v-if="dataForm.selectType === 'startExamine'">
        <view>
          <van-notice-bar left-icon="volume-o" :text="'多项检测同时开始有可能出现检测失败'" />
        </view>
        <view>
          <van-grid direction="horizontal" column-num="2" custom-class="gridClass">
            <van-grid-item use-slot v-for="(item, index) in detectionList" :key="index" custom-class="grid-item-Class">
              <view>{{ item.name }}</view>
              <view class="ml-2">
                <van-checkbox :value="item.flag" shape="square" @change="detectionChange(item, index)"> </van-checkbox>
              </view>
            </van-grid-item>
          </van-grid>
        </view>
        <view class="text-align-center mt-3">
          <van-button type="primary" @click="handleStartExamine">开始检测</van-button>
        </view>
      </view>
      <view v-if="dataForm.selectType === 'timingExamine'">
        <van-notice-bar left-icon="volume-o" :text="'当值为‘无’-关闭定时检测'" />
        <view v-for="(item, index) in detectionList" :key="index">
          <van-cell-group>
            <van-field readonly :label="item.name" :value="filters.timeCut(item.time)" placeholder="请选择时间" @click-input="openTimeSelect(index)" />
          </van-cell-group>
        </view>
        <view class="mt-3 text-align-center">
          <van-button type="primary" custom-style="width:200rpx" @click="timingDetection(2)">确认</van-button>
        </view>
      </view>
    </van-popup>

    <!-- 定位频率设置 -->
    <van-action-sheet @select="frequencySelect" :actions="frequencyActions" @close="dataForm.frequencyShow = false" :show="dataForm.frequencyShow" :title="`定位频率:（当前频率：${filters.minTimeCut(data?.relationObject?.siteRate)}）`"> </van-action-sheet>

    <van-action-sheet title="选择时间（小时）" :show="dataForm.timeValShow" :actions="timeColumns" @close="openTimeSelect" @select="timingDetection(3, $event)" />
  </view>
</template>

<script setup lang="ts">
import useToast from '@/hooks/useToast';
import useModal from '@/hooks/useModal';
import EquipRequest from '@/request/equipRequest';
import filters from '@/utils/filters';
import { navigate } from '@/utils/navigate';

interface IOperatorList {
  name: string;
  type: string;
  iconPath: string;
}

interface IDataForm {
  examineProject: any;
  checkRate: any;
  siteRate: number;
  selectType: string;
  popupShow: boolean;
  timeIndex: number;
  timeValShow: boolean;
  frequencyShow: boolean;
}

interface IDetectionList {
  type: number;
  name: string;
  flag: boolean;
  time: string;
}

const props = defineProps<{ equipInfo: IEquipDetailRes; equipType: number }>();
const data = ref<IEquipDetailRes | undefined>(undefined);
const { showToast } = useToast();
const { showModal } = useModal();

const dataForm = ref<IDataForm>({
  examineProject: [],
  checkRate: [],
  siteRate: 0,
  selectType: '',
  popupShow: false,
  timeIndex: 0,
  timeValShow: false,
  frequencyShow: false,
});

const detectionList = ref<IDetectionList[]>([
  {
    type: 1,
    name: '体温',
    flag: false,
    time: '',
  },
  {
    type: 2,
    name: '心率',
    flag: false,
    time: '',
  },
  {
    type: 3,
    name: '血氧',
    flag: false,
    time: '',
  },
  {
    type: 4,
    name: '血压',
    flag: false,
    time: '',
  },
]);

const operatorList = ref<IOperatorList[]>([
  {
    name: '开始检测',
    type: 'startExamine',
    iconPath: 'i-material-symbols-light:not-started-outline',
  },
  {
    name: '定时检测',
    type: 'timingExamine',
    iconPath: 'i-material-symbols-light:calendar-clock-outline-rounded',
  },
  {
    name: '检测记录',
    type: 'record',
    iconPath: 'i-material-symbols-light:content-paste-search-rounded',
  },
  {
    name: '立即定位',
    type: 'gps',
    iconPath: 'i-material-symbols-light:distance-outline',
  },
  {
    name: '定位频率',
    type: 'timing',
    iconPath: 'i-material-symbols-light:more-time-outline-rounded',
  },
  {
    name: '查看足迹',
    type: 'showFoot',
    iconPath: 'i-material-symbols-light:footprint-outline',
  },
]);

const timeColumns = [
  {
    name: '无',
    val: 0,
  },
  {
    name: 0.5,
    val: 1800,
  },
  {
    name: 1,
    val: 3600,
  },
  {
    name: 2,
    val: 7200,
  },
  {
    name: 3,
    val: 10800,
  },
  {
    name: 4,
    val: 14400,
  },
  {
    name: 5,
    val: 18000,
  },
  {
    name: 6,
    val: 21600,
  },
];

const frequencyActions = [
  {
    name: '2分钟',
    value: 120,
  },
  {
    name: '5分钟',
    value: 300,
  },
  {
    name: '15分钟',
    value: 900,
  },
  {
    name: '30分钟',
    value: 1800,
  },
  {
    name: '1小时',
    value: 3600,
  },
  {
    name: '2小时',
    value: 7200,
  },
  {
    name: '3小时',
    value: 10800,
  },
  {
    name: '5小时',
    value: 18000,
  },
];

//更新检测数据
const updateExamineData = inject<() => void>('updateExamineData');

//更新设备详情数据
const updateDetailData = inject<() => void>('updateDetailData');

//更新定位信息数据
const updateLocationData = inject<() => void>('updateLocationData');

const operatorClick = (type: string) => {
  dataForm.value.selectType = type;
  switch (type) {
    case 'startExamine':
      dataForm.value.popupShow = true;
      break;
    case 'timingExamine':
      let list = detectionList.value;
      EquipRequest.GetCheckRate({
        equipId: data.value!.equipId,
        hasLoading: true,
      }).then((res) => {
        if (res.status === 0) {
          let timearr = res.data.split(',');
          for (let i = 0; i < 4; i++) {
            list[i].time = timearr[i] == '0' ? '无' : timearr[i];
          }
          detectionList.value = list;
        }
      });
      dataForm.value.popupShow = true;
      break;
    case 'record':
      navigate({ url: '/subcontract/equipment/checkReport/index?id=' + data.value?.equipId + '&type=17' });
      break;
    case 'gps':
      EquipRequest.StartSite({
        equipId: data.value?.equipId,
        hasLoading: true,
      }).then((res) => {
        if (res.status === 0) {
          showToast('操作成功');
          setTimeout(() => {
            updateLocationData!();
          }, 1000);
        } else {
          showToast(res.msg);
        }
      });
      break;
    case 'timing':
      dataForm.value.frequencyShow = true;
      break;
    case 'showFoot':
      navigate({ url: '/subcontract/equipment/equipDetail/viewFootPrint?equipId=' + data.value?.equipId });
      break;
  }
};

//开始检测
const handleStartExamine = () => {
  const list = detectionList.value.filter((item) => item.flag).map((item) => item.type);
  if (list.length === 0) {
    showToast('请选择检测项目', 'error');
    return false;
  }
  showModal('预计5-10分钟完成检测，请稍候查看数据', { showCancel: false });
  EquipRequest.StartExamine({
    equipId: data.value?.equipId,
    type: list.join(','),
    hasLoading: true,
  }).then((res) => {
    dataForm.value.popupShow = false;
  });
};

//定时检测
const timingDetection = (type: number, event?: any) => {
  let list = detectionList.value;
  if (type === 2) {
    let arr = [];
    for (let i in list) {
      arr.push(list[i].time === '无' || !list[i].time ? 0 : list[i].time);
    }
    EquipRequest.SetCheckRate({
      equipId: data.value!.equipId,
      checkRate: arr.join(','),
      hasLoading: true,
    }).then((res) => {
      if (res.status === 0) {
        showToast('操作成功', 'success');
        dataForm.value.popupShow = false;
        setTimeout(() => {
          updateExamineData!();
        }, 1000);
      } else {
        showToast(res.msg);
      }
    });
  } else {
    list[dataForm.value.timeIndex].time = event.detail.val;
    detectionList.value = list;
  }
};

const frequencySelect = (event: any) => {
  EquipRequest.SetSiteRate({
    equipId: data.value!.equipId,
    siteRate: event.detail.value,
    hasLoading: true,
  })
    .then((res) => {
      if (res.status === 0) {
        showToast('操作成功', 'success');
        setTimeout(() => {
          updateDetailData!();
          updateLocationData!();
        }, 1000);
      } else {
        showToast(res.msg);
      }
    })
    .catch((err) => {
      showToast(err.msg, 'error');
    });
};

const openTimeSelect = (index: number) => {
  dataForm.value.timeIndex = index;
  dataForm.value.timeValShow = !dataForm.value.timeValShow;
};

const detectionChange = (item: IDetectionList, index: number) => {
  item.flag = !item.flag;
};

const onClose = () => {
  dataForm.value.popupShow = false;
};

watch(
  () => props.equipInfo,
  (newData) => {
    data.value = newData; // 更新 data
  },
  { immediate: true, deep: true }, // 立即执行以确保初始值被捕获
);

watch(
  () => props.equipType,
  (newData) => {
    // 15拐杖 20定位鞋 17手表
    switch (Number(newData)) {
      case 15:
        operatorList.value.splice(0, 3);
        break;
      case 20:
        operatorList.value.splice(0, 3);
        break;
    }
  },
  { immediate: true, deep: true }, // 立即执行以确保初始值被捕获
);
</script>
